package controllers.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.ainibaby6.domain.GetShopItemListRsp;
import com.ainibaby6.domain.IConstants;
import com.ainibaby6.domain.models.ShopItem;
import com.ainibaby6.utils.ModelUtil;
import com.ainibaby6.utils.UUIDGenerator;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import controllers.BaseController;

import play.Play;
import play.db.jpa.JPA;
import play.mvc.Controller;
import play.mvc.Router;
import play.mvc.Router.Route;
import play.mvc.With;

@With(UserLoginFilter.class)
public class ShopItemController extends BaseController
{

    /**
     * 添加商品
     * 
     * @param imagePath
     * @param itemName
     * @param marketPrice
     * @param price
     * @param description
     * @param detailUrl
     * @param type
     * @param imageType
     * @param netImage
     * @throws IOException
     */
    public static void add(File imagePath, String itemName, Double marketPrice,
            Double price, String description, String detailUrl, String type,
            String imageType, String netImage) throws IOException
    {
        String path = null;
        if ("1".equals(imageType))
        {
            path = netImage;
        }
        else
        {

            FileInputStream in = new FileInputStream(imagePath);
            String fileName = UUIDGenerator.generate()
                    + imagePath.getName().substring(
                            imagePath.getName().lastIndexOf('.'));

            path = "public/shopItemImage/" + fileName;
            File img = new File(Play.applicationPath + "/" + path);
            FileOutputStream out = new FileOutputStream(img);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
            path = "/" + path;
        }
        ShopItem item = new ShopItem();
        item.setCreateTime(new Date());
        item.setModifyTime(new Date());
        item.setItemId(UUIDGenerator.generate());
        item.setItemName(itemName);
        item.setImagePath(path);
        item.setDescription(description);
        item.setMarketPrice(marketPrice);
        item.setPrice(price);
        item.setType(type);
        item.setDetailUrl(detailUrl);
        item.save();
        renderArgs.put("tip", "success");
        render("/manager/Manager/addShopItem.html");
    }

    /**
     * 修改商品
     * 
     * @param itemId
     * @param imagePath
     * @param itemName
     * @param marketPrice
     * @param price
     * @param description
     * @param detailUrl
     * @param type
     * @param imageType
     * @param netImage
     * @throws IOException
     */
    public static void modify(String itemId, File imagePath, String itemName,
            Double marketPrice, Double price, String description,
            String detailUrl, String type, String imageType, String netImage)
            throws IOException
    {
        String path = null;
        if ("1".equals(imageType) && StringUtils.isNotEmpty(netImage))
        {
            path = netImage;
        }
        else if (imagePath != null)
        {
            FileInputStream in = new FileInputStream(imagePath);
            String fileName = UUIDGenerator.generate()
                    + imagePath.getName().substring(
                            imagePath.getName().lastIndexOf('.'));

            path = "public/shopItemImage/" + fileName;

            FileOutputStream out = new FileOutputStream(path);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
            path = "/" + path;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("modifyTime", new Date());
        if (path != null)
        {
            map.put("imagePath", path);
        }
        if (StringUtils.isNotEmpty(itemName))
        {
            map.put("itemName", itemName);
        }
        if (StringUtils.isNotEmpty(description))
        {
            map.put("description", description);
        }
        if (marketPrice != null)
        {
            map.put("marketPrice", marketPrice);
        }
        if (price != null)
        {
            map.put("price", price);
        }
        if (StringUtils.isNotEmpty(detailUrl))
        {
            map.put("detailUrl", detailUrl);
        }
        if (StringUtils.isNotEmpty(type))
        {
            map.put("type", type);
        }
        ModelUtil.update(ShopItem.class, itemId, map);
        renderArgs.put("tips", "修改成功");
        render("/manager/Manager/getShopItemList.html");
    }

    public static void getList(int page, int num, String type)
    {
        if (page <= 0)
        {
            page = 1;
        }
        if (num <= 0)
        {
            num = 10;
        }
        String hql = null;
        String countHql = null;
        if (StringUtils.isEmpty(type))
        {
            hql = "from ShopItem order by modifyTime desc";
            countHql = "select count(itemId) from ShopItem";
        }
        else
        {
            hql = "from ShopItem where type=? order by modifyTime desc";
            countHql = "select count(itemId) from ShopItem where type=?";
        }
        Query countQ = JPA.em().createQuery(countHql);
        if (StringUtils.isNotEmpty(type))
        {
            countQ.setParameter(1, type);
        }
        int count = ((Long) countQ.getResultList().get(0)).intValue();

        int pageCount = (count - 1) / num + 1;
        if (pageCount <= 0)
        {
            pageCount = 1;
        }
        if (page > pageCount)
        {
            page = pageCount;
        }

        // 响应json
        GetShopItemListRsp rsp = new GetShopItemListRsp();
        rsp.setPage(page);
        rsp.setPageCount(pageCount);
        rsp.setNumPerPage(num);
        rsp.setTotalNum(count);
        if (count > 0)
        {
            Query q = JPA.em().createQuery(hql);
            if (StringUtils.isNotEmpty(type))
            {
                q.setParameter(1, type);
            }
            q.setMaxResults(num);
            q.setFirstResult((page - 1) * num);
            rsp.setItemList(q.getResultList());
        }
        renderJSON(gson.toJson(rsp));
    }

    public static void toModify(String id)
    {
        ShopItem item = ShopItem.findById(id);
        renderArgs.put("item", item);
        render("/manager/Manager/modifyShopItem.html");
    }

    public static void delete(String id)
    {
        if (StringUtils.isEmpty(id))
        {
            return;
        }
        ShopItem.delete("delete from ShopItem where itemId=?", id);
    }

    /**
     * 首页需要ajax加载的html数据
     * 
     * @param type
     * @param page
     */
    public static void getListAsHtml(String type, int page)
    {
        if (page <= 1)// 第一页不用获取
        {
            return;
        }
        if (IConstants.BOY_SHOP_ITEM.equals(type)
                || IConstants.GIRL_SHOP_ITEM.equals(type))
        {
            String hql = "from ShopItem where type=? order by modifyTime desc";
            Query q = JPA.em().createQuery(hql);
            q.setParameter(1, type);
            q.setMaxResults(10);
            q.setFirstResult((page - 1) * 10);
            List<ShopItem> items = q.getResultList();
            // 有数据才进行渲染
            if (CollectionUtils.isNotEmpty(items))
            {
                renderArgs.put("_items", q.getResultList());
                render("/tags/itemsView.html");
            }
        }
    }
}
